import { put, fork, take, call } from "redux-saga/effects";
// import { replace } from "react-router-redux"; // goBack
import { userService } from "../services/api/";
import * as actions from "../actions";
// import { delay } from 'redux-saga'
import { USER_LOGIN_REQUEST } from "../constants/actionTypes";

function* loginSaga(payload) {
  try {
    yield put(actions.fetchRequest({ text: "登录中" })); // 全局请求开始

    const response = yield call(userService.loginByName, payload);
    yield put(actions.fetchSuccess()); // 全局请求成功

    yield put(actions.postLoginSuccess(response)); // 登录请求的成功
    // yield put(replace("http://i.veryeast.cn"));
  } catch (error) {
    yield put(actions.fetchFailed()); // 全局请求失败
    yield put(actions.postLoginFailed(error)); // 登录请求的失败
  }
}

export function* watchLogin() {
  while (true) {
    const { payload } = yield take(USER_LOGIN_REQUEST);
    yield fork(loginSaga, payload);
  }
}
